<?php

Yii::import("application.components.evaluators.CompilerBase");

class SinglesourceCompiler extends CompilerBase {

    private $language;

    public function __construct($request) {
        parent::__construct($request);
    }

    public function setLanguage($language) {
        $this->language = $language;
    }

    protected function afterCompile() {
        
    }

    protected function beforeCompile() {
        $this->targetFilePath = $this->getGradingDirectory() . "/" . $this->requestModel->source_file;
        file_put_contents($this->targetFilePath , $this->requestModel->file);
    }
    
    public function setTarget($target) {
    }

    /**
     * Membuat berkas script (.sh) untuk kemudian dijalankan oleh grader 
     */
    protected function generateExecutionScript() {
        if ($this->compileReturnValue == 0) {
            $this->executionScriptPath = $this->gradingDirectory . "/execute.sh";
            $executionCommand = "";
            if ($this->language == "java") {
                $targetClassFile = basename($this->outputFilePath, ".class") . "\n";
                $executionCommand = "cd $this->gradingDirectory\n/usr/bin/java $targetClassFile";
            } else {
                $executionCommand = $this->outputFilePath;
            }
            file_put_contents($this->executionScriptPath, $executionCommand);
        } else {
            $this->executionScriptPath = "";
        }
    }

    protected function doCompile() {
        $ext = end(explode(".", $this->targetFilePath));
        $this->language = $ext;
        if ($ext != "java")
            $this->outputFilePath = tempnam($this->gradingDirectory, "lz-single-");
        $compileCommand = "";

        switch ($ext) {
            case "cpp":
                $compileCommand = "/usr/bin/g++ -o $this->outputFilePath $this->targetFilePath";
                break;
            case "pas":
                $compileCommand = "/usr/bin/fpc $this->targetFilePath -o$this->outputFilePath";
                break;
            case "c":
                $compileCommand = "/usr/bin/gcc -o $this->outputFilePath $this->targetFilePath";
                break;
            case "java":
                $compileCommand = "/usr/bin/javac $this->targetFilePath -d " . $this->gradingDirectory;
                $this->outputFilePath = Yii::app()->params['config']['compiler']['temp_dir'] . "/" . basename($this->targetFilePath, ".java") . ".class";
                break;
        }

        exec("$compileCommand 2>&1", $output, $return);
        $this->compileOutput = implode("\n", $output);
        $this->compileReturnValue = $return;
    }

}

?>
